<?php
defined('_JEXEC') or die();

class WrdControllerAtransaction extends JControllerLegacy 
{
	protected  $option;
	protected  $controller;
	
	function __construct( $default = array()){
    		$this->option = 'com_wrd';
    		$this->controller = 'atransaction';
			parent::__construct( $default );
	}

	function display()
	{
		switch( $this->getTask() ){
		case 'add':
			$user = JFactory::getUser();					
			JRequest::setVar( 'hidemainmenu', 1 );
			JRequest::setVar( 'layout', 'form'  );
			JRequest::setVar( 'view'  , 'atransaction');					
			break;
		default:
			JRequest::setVar( 'view'  , 'atransaction');
			break;
		}
		parent::display();
	}
        
      //save profile info
    function save(){
       	
		$post=JRequest::get('post');
		// echo "<pre>";print_r($post);exit;
	   	$post['created_date'] = date("Y-m-d H:i:s");
       	$post['convert'] = 1 ;
           
       	$db = &JFactory::getDbo();
      	$params = JComponentHelper::getParams('com_wrd');
	   	$model=$this->getModel('atransaction');
	   	//get date current
		if($post['id'] == 0)
       		$id_category = $model->store($post,'atransaction');
       
		if(intval($post['id']) != 0 && intval($post['point_id']) != 0){
			
			$obj = new stdClass();
			$obj->id = $post['point_id'];
			
			
			if($post['expire'] !='0000-00-00' && $post['expire'] !=''){
				$new_expire = strtotime($post['expire'].' 23:59:59');

				if($new_expire < time()){
					$obj->expired = 1;
				}
				else{
					$obj->expired = 0;
				}
			}
			else{
				$obj->expired = 0;
			}
			
			

			$obj->expire = $post['expire'];
			$obj->outlet = $post['outlet'];
			$db->updateObject('#__wrd_point', $obj, 'id');
			
			$query = 'SELECT * FROM `#__wrd_point` WHERE id = '.$post['point_id'];
			$expired_rs = $db->setQuery($query)->loadObjectList();
			
			foreach ($expired_rs as $expired){
				$query = 'SELECT * FROM `#__wrd_point`
					WHERE
							type = 9 AND
							user_id = '.$expired->user_id.' AND
							transaction = "'.$expired->transaction.'"';
					
				$rs1 = $db->setQuery($query)->loadObjectList();
					
				foreach ($rs1 as $row){
					$point_obj = new stdClass();
					$point_obj->id = $row->id;
					$point_obj->expired = $obj->expired;
					$point_obj->outlet = $obj->outlet;
					$db->updateObject('#__wrd_point', $point_obj, 'id');
				}
			}
			
			
			$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['profile_id'].'&layout=form&tab=transaction','Saved');
			return true;	
		}
		
	   //Update in to wrd_spending_summary
	   $month = date('m',strtotime($post['date_receipt']));
	   $year = date('Y',strtotime($post['date_receipt']));
	 
		if($year < date('Y')||(($year == date('Y'))&&($month <= date('m')))){
			while(($month != date('m'))||($year != date('Y'))){
				WrdHelper::uSummarySpend($post['vip_number'],$year,$month);
				if($month+1 <=12) ++$month;
				else {$month = 1;++$year;}
			}
		}
		
		WrdHelper::uSummarySpend($post['vip_number'],date('Y'),date('m'));
		
		$totalSpend = WrdHelper::getTotalTransaction($post['vip_number']);
		$sql = 'UPDATE #__wrd_profile SET total_spend = '.$totalSpend->total .' WHERE member_id = '.$post['vip_number'];
		$db->setQuery($sql);
		$db->query();
		
       if($id_category!=0){
			$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['profile_id'].'&layout=form&tab=transaction','Saved');
			return true;
       }
       else{
            $this->setRedirect('index.php?option=com_wrd&controller=atransaction','Error Saved');
            return false;
       }
    }    
    
	function cancel(){
		$post=JRequest::get('post');
		$this->setRedirect('index.php?option=com_wrd&controller=profile&id='.$post['profile_id'].'&layout=form&tab=transaction');
	}

    function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to delete' ) );
		}

		$model = $this->getModel('atransaction');
		if(!$model->delete($cid)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		$this->setRedirect( 'index.php?option=com_wrd&controller=atransaction' );
	}
   
    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>' ) );
		}

		$model = $this->getModel('atransaction');
		if(!$model->publish($cid, 1)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		$this->setRedirect( 'index.php?option=com_wrd&controller=atransaction' );
	}

	function unpublish(){
		
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>'  ) );
		}

		$model = $this->getModel('atransaction');
		
		if(!$model->publish($cid, 0)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		$this->setRedirect( 'index.php?option=com_wrd&controller=atransaction' );
	}
	
	function saveorder(){
		JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Get the arrays from the Request
		$order	= JRequest::getVar('order',	null, 'post', 'array');
		$originalOrder = explode(',', JRequest::getString('original_order_values'));

		// Make sure something has changed
		if (!($order === $originalOrder)) {
			// Check for request forgeries.
			JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
	
			// Get the input
			$pks	= JRequest::getVar('cid',	null,	'post',	'array');
			$order	= JRequest::getVar('order',	null,	'post',	'array');
	
			// Sanitize the input
			JArrayHelper::toInteger($pks);
			JArrayHelper::toInteger($order);
	
			// Get the model
			$model = $this->getModel('atransaction');
	
			// Save the ordering
			$return = $model->saveorder($pks, $order,'atransaction');
	
			if ($return === false)
			{
				// Reorder failed
				$message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError());
				$this->setRedirect(JRoute::_('index.php?option=com_wrd&controller=atransaction', false), $message, 'error');
				return false;
			} else{
				// Reorder succeeded.
				$this->setMessage(JText::_('JLIB_APPLICATION_SUCCESS_ORDERING_SAVED'));
				$this->setRedirect(JRoute::_('index.php?option=com_wrd&controller=atransaction', false));
				return true;
			}
		} else {
			// Nothing to reorder
			$this->setRedirect(JRoute::_('index.php?option=com_wrd&controller=atransaction', false));
			return true;
		}
	}
	
	function orderdown(){
		$this->reorder($task = 'orderdown');
	}
	
	function orderup(){
		$this->reorder($task = 'orderup');
	}
	
	
	function reorder($task)
	{
		// Check for request forgeries.
		JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Initialise variables.
		$user	= JFactory::getUser();
		$ids	= JRequest::getVar('cid', null, 'post', 'array');
		$inc	= ($task == 'orderup') ? -1 : +1;

		$model = $this->getModel('atransaction');
		$return = $model->reorder($ids, $inc,'atransaction');
		if ($return === false) {
			// Reorder failed.
			$message = JText::sprintf('JLIB_APPLICATION_ERROR_REORDER_FAILED', $model->getError());
			$this->setRedirect(JRoute::_('index.php?option='.$this->option.'&controller='.$this->controller, false), $message, 'error');
			return false;
		} else {
			// Reorder succeeded.
			$message = JText::_('JLIB_APPLICATION_SUCCESS_ITEM_REORDERED');
			$this->setRedirect(JRoute::_('index.php?option='.$this->option.'&controller='.$this->controller, false), $message);
			return true;
		}
	}
}